package com.example.computer_component_manager.volley

import com.android.volley.NetworkResponse
import com.android.volley.Response
import com.android.volley.toolbox.HttpHeaderParser
import com.android.volley.toolbox.JsonArrayRequest
import org.json.JSONArray
import java.nio.charset.Charset

/**
 * 自定义JsonArrayRequest
 * 解决Session会话保持问题
 *
 * @author 1923111015董寺卓
 */

class MyJsonArrayRequest(
    method: Int,
    url: String?,
    jsonRequest: JSONArray?,
    listener: Response.Listener<JSONArray>?,
    errorListener: Response.ErrorListener?,
) : JsonArrayRequest(method, url, jsonRequest, listener, errorListener) {

    override fun parseNetworkResponse(response: NetworkResponse): Response<JSONArray> {
        // 检查本地是否存在session，如无，则保存session到本地
        VolleyApplication.instance.checkSessionCookie(response.headers!!)
        val jsonArray = JSONArray(String(response.data,
            Charset.forName(HttpHeaderParser.parseCharset(response.headers, PROTOCOL_CHARSET))))
        return Response.success(jsonArray, HttpHeaderParser.parseCacheHeaders(response))
    }

    override fun getHeaders(): MutableMap<String, String> {
        var headers = super.getHeaders()
        headers = VolleyApplication.instance.addSessionCookie(headers)
        return headers
    }
}